﻿using BLL;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Serialization;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using Tools;
using System;
using Entity.ViewEntity;
using System.Reflection;
using YunProject.Controllers.Base;
using Entity;
using SysFramework;
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using log4net;

namespace YunProject.Controllers
{
    public class SystemController : BaseController
    {
        SystemManagement sysBLL;
        PowerManagement powerBLL;
        UserManagement userBLL;
        InventoryBLL venBLL;
        WareHouseBLL wareBLL;
        public ILog log = LogManager.GetLogger(typeof(SystemController));
        public SystemController()
        {
            sysBLL = new SystemManagement();
            userBLL = new UserManagement();
            powerBLL = new PowerManagement();
            venBLL = new InventoryBLL();
            wareBLL = new WareHouseBLL();
        }

        #region
        [AllowAnonymous]
        public IActionResult login()
        {
            return View();
        }
        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 用户列表页
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult UserList()
        {
            return View();
        }
        /// <summary>
        /// 权限角色
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult PowerRole()
        {
            return View();
        }
        [Authorize]
        public ActionResult UpdatePowerRole()
        {
            return View();
        }
        [Authorize]
        public ActionResult MenuInfo()
        {
            return View();
        }
        [Authorize]
        public ActionResult UpdateMenu()
        {
            return View();
        }
        [Authorize]
        public ActionResult MenuOperate()
        {
            return View();
        }
        [Authorize]
        public ActionResult SetRolePowers()
        {
            return View();
        }
        [Authorize]
        public ActionResult UpdateUser()
        {
            return View();
        }
        [Authorize]
        public ActionResult ParameterInfo()
        {
            return View();
        }
        [Authorize]
        public ActionResult UpdateParameter()
        {
            return View();
        }
        [Authorize]
        public ActionResult UserPower()
        {
            return View();
        }
        [Authorize]
        public ActionResult QueryWeb()
        {
            return View();
        }
        [Authorize]
        public ActionResult MoreQuery()
        {
            return View();
        }
        [Authorize]
        public ActionResult Powers()
        {
            return View();
        }
        [Authorize]
        public ActionResult OperatePower()
        {
            return View();
        }
        [Authorize]
        public ActionResult CustomBase()
        {
            return View();
        } 
        [Authorize]
        public ActionResult UpdateCustomBase()
        {
            return View();
        }

        [Authorize]
        public ActionResult ChanagePwd()
        {
            return View();
        }

        #endregion

        /// <summary>
        /// 系统账号登录方法
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> userLogin(string userInfo)
        {
            var rsl = sysBLL.login(userInfo);
            int days = int.Parse(AppSettingHelper.ReadAppSettings("CookieLostDays"));
            if (rsl.Result)
            {
                var dataStr = JsonConvert.SerializeObject(rsl.Data);
                dataStr = Tools.Encryption.DesEncrypt(dataStr);
                var claims = new List<Claim>() {
                new Claim("userCookie",dataStr)
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    principal, new AuthenticationProperties()
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.UtcNow.AddDays(days),
                        AllowRefresh = true
                    });
            }
            return Json(rsl);
        }
        /// <summary>
        /// 导航菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Navigation()
        {
            var rsl = new ReturnResult();
            var userObj = LoginInfo();
            if (userObj != null)
            {
                rsl = sysBLL.Navigation(userObj["userCode"].ToString());
            }
            return Json(rsl);
        }
        /// <summary>
        /// 菜单界面权限
        /// </summary>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetWebPowers(string menuCode)
        {
            var userObj = LoginInfo();
            return Json(powerBLL.GetUserPower("", menuCode, userObj));
        }

        [HttpPost]
        public JsonResult GetTopMenu()
        {
            return Json(sysBLL.GetTopMenu());
        }
        /// <summary>
        /// 权限角色更新方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdatePowerRole(string datas)
        {
            var rsl = new ReturnResult();
            var userObj = LoginInfo();
            if (userObj != null)
            {
                rsl = powerBLL.UpdatePowerRole(datas, userObj["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult getRoleById(string dataKey)
        {
            return Json(powerBLL.getRoleById(dataKey));
        }
        [HttpPost]
        public JsonResult getEnableMenuInfo()
        {
            return Json(sysBLL.getEnableMenuInfo());
        }
        [HttpPost]
        public JsonResult getDictionaryInfo(string type)
        {
            return Json(sysBLL.getDictionaryInfo(type, ""));//
        }
        [HttpPost]
        public JsonResult GetColumnsFields(string menuCode)
        {
            return Json(sysBLL.GetWebFields(menuCode));
        }
        [HttpPost]
        public JsonResult layUiTree()
        {
            return Json(powerBLL.layUiTree(""));
        }
        [HttpPost]
        public JsonResult GetUserInfo()
        {
            var rsl = new ReturnResult();
            var userObj = LoginInfo();
            if (userObj != null)
            {
                rsl = userBLL.GetUserInfo();
            }
            return Json(rsl);
        }
        /// <summary>
        /// 权限角色删除方法
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelRolePowers(int dataId)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.DelRolePowers(dataId, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpGet]
        public JsonResult initSystem(string pars, string pType)
        {
            return new JsonResult(sysBLL.InitSystem(pars, pType));

        }


        [HttpPost]
        public JsonResult UpdatePowers(string datas)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.UpdatePowers(datas, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }

        [HttpPost]
        public JsonResult GetWebPowerByCode(string menuCode,string groupCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.GetRoleWebOperate(menuCode,groupCode, userInfo["userCode"].ToString(), userInfo["isAdmin"].ToString());
            }
            return Json(rsl);
        }

        [HttpPost]
        public JsonResult GetDeptInfo()
        {
            return Json(userBLL.GetDeptInfo());
        }
        [HttpPost]
        public JsonResult getUserInfoByCode(string userCode, string dataId)
        {
            return Json(userBLL.getUserInfoByCode(userCode, dataId));
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateUser(string data)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = userBLL.UpdateUser(data, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult ReSetPwd(string userCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = userBLL.ReSetPwd(userCode);
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult DelUserInfo(string userCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = userBLL.DelUserInfo(userCode, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult SaveMenuInfo(string datas)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = sysBLL.SaveMenuInfo(datas, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult DelMenuInfo(string menuCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = sysBLL.DelMenuInfo(menuCode, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult SaveParameter(string datas)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = sysBLL.SaveParameter(datas, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult getMenuByCode(string menuCode)
        {
            return Json(sysBLL.getMenuByCode(menuCode));
        }
        [HttpPost]
        public JsonResult DelParmeter(string parCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = sysBLL.DelParmeter(parCode, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
      
        [HttpPost]
        public JsonResult GetUserWebOperate(string menuCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.GetUserWebOperate(menuCode, userInfo["userCode"].ToString(), userInfo["isAdmin"].ToString(), userInfo["powerRole"].ToString());
            }
            return Json(rsl);
        }
        
        [HttpPost]
        public JsonResult SaveRolePower(string groupCode, string menuCode, string powers)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.SaveRolePower(groupCode,menuCode, powers,userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult CleanWebPower(string groupCode, string menuCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.CleanWebPower(groupCode, menuCode, userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult DelPowerByCode(string pCode)
        {
            var rsl = new ReturnResult();
            var userInfo = LoginInfo();
            if (userInfo != null)
            {
                rsl = powerBLL.DelPowerByCode(pCode,userInfo["userCode"].ToString());
            }
            return Json(rsl);
        }

        [HttpPost]
        public JsonResult getParameterByCode(string parCode)
        {
            return Json(sysBLL.getParameterByCode(parCode));
        }
        [HttpPost]
        public JsonResult saveMenuPower(string menuCode, string powerValue)
        {
            return Json(powerBLL.SaveMenuPower(menuCode, powerValue));
        }
        [HttpPost]
        public JsonResult SaveUserRole(string userCode, string groupCode)
        {
            return Json(userBLL.SaveUserRole(userCode, groupCode));
        }
        [HttpPost]
        public JsonResult cleanUserRole(string userCode)
        {
            return Json(userBLL.cleanUserRole(userCode));
        }
        [HttpPost]
        public JsonResult AddQueField(string datas)
        {
            return Json(sysBLL.AddQueField(datas));
        }
        [HttpPost]
        public JsonResult DelQueField(string datas)
        {
            return Json(sysBLL.DelQueField(datas));
        }
        [HttpPost]
        public JsonResult LoadQueryFields(string menuCode)
        {
            return Json(sysBLL.LoadQueryFields(menuCode));
        }
        [HttpPost]
        public JsonResult SaveSingleWebPower(string dataId,string field,string value)
        {
            return Json(powerBLL.SaveSingleWebPower(dataId,field,value));
        }
        [HttpPost]
        public JsonResult DelWebPower(string dataId)
        {
            return Json(powerBLL.DelWebPower(dataId));
        }
        
        /// <summary>
        /// 数据同步
        /// </summary>
        /// <param name="syncCode"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public JsonResult SyncData(string syncCode, bool isAuto = false)
        {
            var rsl = new ReturnResult();
            if (AppSettingHelper.ReadAppSettings("ConntectERP") != "1")
            {
                rsl.Message = "没有开启ERP同步权限";
            }
            else
            {
                string userCode = "admin", erpCode = "";
                if (!isAuto)
                {
                    var userInfo = LoginInfo();
                    userCode = userInfo["userCode"].ToString();
                    erpCode = userInfo["baseCode"].ToString();
                }
                else
                {
                    erpCode = sysBLL.getDefaultBaseCode();
                }
                if (syncCode == "user")
                {
                    rsl = userBLL.SyncUserData(userCode, erpCode);
                }
                else if (syncCode == "ven")
                {
                    rsl = venBLL.SyncInventory(userCode, erpCode, false, true);
                }
                else if (syncCode == "wareHouse")
                {
                    //同步仓库无货位
                    rsl = wareBLL.SyncWareHouse(userCode, erpCode, false);
                }
                else if (syncCode == "Cu" || syncCode == "Sp")
                {
                    CustomBLL cuBLL = new CustomBLL();
                    rsl = cuBLL.SyncCustom(userCode, erpCode, syncCode, true);
                }
                else if (syncCode == "bg")
                {
                    rsl = venBLL.SyncBanGunInData(erpCode);
                    if(rsl.Result)
                        rsl = venBLL.SyncBanGunData(erpCode);
                }

            }
            return Json(rsl);
        }
        [HttpPost]
        public JsonResult GetTableCloums(string tCode)
        {
            var info = sysBLL.GetTableCloums(tCode);
            return Json(sysBLL.GetTableCloums(tCode));
        }
        [HttpGet]
        public JsonResult getDataList(string page, string limit, string condition, string dataType)
        {
            var rsl = new ReturnResult();
            string pageCount = "1";
            string msg = "";
            var datas = new object();
            var userObj = LoginInfo();
            if (dataType == "menu")
            {
                rsl = sysBLL.getMenuList(page, limit, condition, userObj["userCode"].ToString(), ref pageCount);
            }
            else if (dataType == "tcc")
            {
                rsl = sysBLL.LoadQueryFieldsList(condition);
            }
            else if (dataType == "user")
            {
                rsl = userBLL.getUserPageList(page, limit, condition, userObj, ref pageCount);
            }
            else if (dataType == "par")
            {
                rsl = sysBLL.getParametersList(page, limit, ref pageCount, condition);
            }
            else if (dataType == "sysPower")
            {
                rsl = powerBLL.GetWebPowers(page, limit, condition, ref pageCount);
            }
            else if (dataType == "pRole")
            {
                rsl = powerBLL.getPowerRoleList(page, limit, ref pageCount, condition);
            }
            else if (dataType == "powers")
            {
                rsl = powerBLL.GetPowersList(page, limit, ref pageCount, condition); 
            }
            else if (dataType == "cdb")
            {
                rsl = sysBLL.CustomBaseInfo();
            }
            if (rsl.Result)
            {
                datas = rsl.Data;
            }
            else
            {
                msg = rsl.Message;
            }
            var dic = new Dictionary<string, object>();
            dic["count"] = pageCount;
            dic["msg"] = msg;
            dic["code"] = "0";
            dic["data"] = datas;
            return new JsonResult(dic);

        }

        [HttpPost]
        public JsonResult SaveBaseData(string datas)
        {
            return Json(sysBLL.SaveBaseData(datas));
        }
        [HttpPost]
        public JsonResult getCustomBaseByCode(string dataId)
        {
            return Json(sysBLL.getCustomBaseByCode(dataId));
        }
        [HttpPost]
        public JsonResult delCustomBaseById(string dataId)
        {
            return Json(sysBLL.delCustomBaseById(dataId));
        }

        [HttpPost]
        public JsonResult ChanagePWD(string oldPwd, string newPwd)
        {
            var userObj = LoginInfo();
            return Json(userBLL.ChanagePWD(userObj["userCode"].ToString(),oldPwd, newPwd));
        }

    }
}
